package io.eyer.rpc;

import io.eyer.nio.core.event.Acceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by 青木 on 2015/8/18.
 */
public class Server extends Thread implements Closeable {
    private static Logger logger = LoggerFactory.getLogger(Server.class);
    private String host;
    private int port;
    private Acceptor accpectEventLoop;
    ServerSocketChannel serverSocketChannel;

    public Server(String host, int port, Acceptor accpectEventLoop) {
        this.host = host;
        this.port = port;
        this.accpectEventLoop = accpectEventLoop;
    }

    @Override
    public void run() {
        try {
            serverSocketChannel = (ServerSocketChannel) ServerSocketChannel.open().bind(new InetSocketAddress(host, port)).configureBlocking(false);
            accpectEventLoop.register(serverSocketChannel);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    public void close() {
       try {
           serverSocketChannel.close();
           accpectEventLoop.close();
       }catch (Exception e){
           logger.error(e.getMessage(),e);
       }
    }
}
